package com.langyiquan.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.langyiquan.exception.http.PayException;
import com.langyiquan.service.AliPayService;
import org.springframework.stereotype.Service;

@Service
public class AliPayServiceImpl implements AliPayService {

    @Override
    public String placeOrder(AlipayTradePagePayRequest alipayRequest,AlipayClient alipayClient, String orderId, String userId) {

        // 商户订单号, 商户网站订单系统中唯一订单号, 必填
        String out_trade_no = orderId;

        // 付款金额, 必填 单位元
        // String total_amount = CurrencyUtils.fenToYuan(waitPayOrder.getPayAmount());
        String total_amount = "0.01";	// 测试用 1分钱

        // 订单名称, 必填
        String subject = "付款用户[" + userId + "]";

        // 商品描述, 可空, 目前先用订单名称
        String body = subject;

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1d";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String alipayForm = "";
        try {
            alipayForm = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new PayException(7002);
        }

        return alipayForm;

    }


}
